/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the ViewMyCurrency extension.
 *
 * The Initial Developer of the Original Code is
 * Will Moffat.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

//dump("// $Id: WILL_GiveFeedbackManager.js,v 1.13 2007/02/27 12:17:52 Will Exp $;\n");

VMC.giveFeedbackManager = null;

VMC.giveFeedbackLoad = function () {
  var url = '';
  var problemText = '';
  if (window.arguments && window.arguments.length==2) {
    url         = window.arguments[0];
    problemText = window.arguments[1];
  }
  VMC.giveFeedbackManager = new VMC.GiveFeedbackManager(url,problemText);
};


VMC.GiveFeedbackManager = function(currentUrl,problemText) {
  var self=this;

  this.doFinish = doFinish;
  this.doUpdateComment = doUpdateComment;
  this.doValidateSummary = doValidateSummary;

  this._init    = _init;  
  this._getTechInfo = _getTechInfo;

  this._init();

  function _init() {
    var finishButton = VMC.ge('VMC-feedback-wizard').getButton('finish');
    finishButton.label="Add to website...";
    finishButton.setAttribute('tooltiptext',"Opens the ViewMyCurrency blog and copy+pastes this comment.");

    this.doValidateSummary();

    VMC.updateAndAddHandlerToLinks();

    VMC.ge('VMC-url-textbox').value=currentUrl;
    VMC.ge('VMC-problem-textbox').value=problemText;

    // show the extra info about the web page if text was selected
    var isCommentAboutPage = (currentUrl && problemText);
    var checkbox = VMC.ge('VMC-webpage-checkbox');
    checkbox.checked = isCommentAboutPage;
    checkbox.doCommand();

  }

  function doValidateSummary() {
    var summaryBox = VMC.ge('VMC-summary-textbox');
    var text=summaryBox.value;
    if (!text || !text.length) { VMC.setOutline(summaryBox,'solid 3px red') } //invalid!
    else                       { VMC.setOutline(summaryBox,'')                      } //OK
  }

  function _getTechInfo() {
    var info = '';

    try {
      var pushInfo = function(varName,varValue) { info += varName+': ['+varValue+'], ' }; 
      pushInfo('Browser',navigator.userAgent);
      
      if (!window.opener) { pushInfo('opener','missing') }
      else if (!window.opener.VMC) { pushInfo('VMC','missing') }
      else if (!window.opener.VMC.gui) { pushInfo('VMC.gui','missing') }
      else if (!window.opener.VMC.gui._viewMyCurrency) { pushInfo('VMC.gui._viewMyCurrency!','missing') }
      else {
	var vmc = window.opener.VMC;
	var viewMyCurrency = vmc.gui._viewMyCurrency;
	pushInfo('ver',vmc.VERSION);
	pushInfo('source', viewMyCurrency._sourceCurrencyList );
	pushInfo('target', viewMyCurrency._targetCurrencyList );
	pushInfo('current',viewMyCurrency.getTargetCurrency() );
      }
      
      var accept_languages = nsPreferences.getLocalizedUnicharPref('intl.accept_languages');
      pushInfo('langs',accept_languages);

      var currentTheme = nsPreferences.copyUnicharPref('general.skins.selectedSkin','???');
      pushInfo('theme',currentTheme);

    } catch(e) { info += 'ERROR: '+e }
    
    return info;
  }

  function doUpdateComment() {
    var commentBox = VMC.ge('VMC-comment-textbox');
    var comment='';
    var getText = function(textbox) { return VMC.ge(textbox).value }

    comment += getText('VMC-feedbacktype-menulist')+' '+getText('VMC-summary-textbox') +'\n';
    comment += '\n' +getText('VMC-details-textbox') +'\n';

    if (VMC.ge('VMC-webpage-checkbox').checked) {
      comment += '\n';
      comment += 'At ' + getText('VMC-url-textbox') + '\n';
      comment += '------- I saw: ------------\n';
      comment += getText('VMC-problem-textbox') + '\n';
      comment += '------- Expected to see: --\n';
      comment += getText('VMC-expected-textbox') + '\n';
    }
    comment += '-----------------------\n';
    comment += this._getTechInfo() + '\n';
    comment += '-----------------------\n';

    commentBox.value = comment;
  }

  // WILL: I had to removed the error handling as any error on a page would trigger the handler, even if the page does finally load. TODO: check for missing 'load' event.
  // The conversion profiles should turn VMC off when we go to an offical ViewMyCurrency page.
  function doFinish() {
    var commentText = VMC.ge('VMC-comment-textbox').value;

    VMC.copyToClipboard('To: vmc_bugs@hamstersoup.com\n'+commentText); // so that the user can paste it into an email if anything goes wrong

    // The #name ref is perserved during HTTP redirect. '?' args must come first
    var releaseNotesURL="http://hamstersoup.com/ViewMyCurrency/bounce/GiveFeedback?ver="+VMC.VERSION+'#commentform';
    // Should bounce to something like http://viewmycurrency.wordpress.com/2006/02/08/firefox-currency-converter-viewmycurrency-0389-alpha-released/#commentform"
    var alertOfLastResort = 'Please email me.\nStart a blank email and press paste (everything has been stored in the clipboard)';
    var myWindow = window.open(releaseNotesURL,'WILL_test');
    if (!myWindow) {alert('Could not open blog. \n'+alertOfLastResort); }

    var newMainWindow = VMC.getBrowserWindow();
    var newBrowser = newMainWindow.getBrowser();

    var delayedFunc = function() {
      newBrowser.removeEventListener('DOMContentLoaded', delayedFunc, false); // we should only get called once
      // WILL: removed, any error on page will trigger this: newBrowser.removeEventListener('error',delayedFunc, true); // we should only get called once
      var commentTextBox = myWindow.document.getElementById('comment');
      if (!commentTextBox) {
	// note we use myWindow to display the alert. Otherwise the new window is hidden
	myWindow.alert('Internal error\n'+ /* ViewMyCurrency Feedback Wizard could not find the ViewMyCurrency blog.\n'+ */
		       alertOfLastResort);
      } else {
	commentTextBox.value=commentText;
	var sayItButton = myWindow.document.getElementsByName('submit')[0]; //getElementById('submit');
	if (sayItButton) { newMainWindow.VMC.blink(sayItButton,8); }
      }
    };

    newBrowser.addEventListener('DOMContentLoaded', delayedFunc, false );
    // WILL: removed, any error on page will trigger this:  newBrowser.addEventListener('error',delayedFunc, false );

    // WILL: Useful code for debugging events
//     var events = ['DOMContentLoaded','abort','load','blur','mousedown','click',/*'mousemove'*/,'change','mouseout','dblclick',/*'mouseover'*/,'dragdrop','mouseup','error','move','focus','reset','keydown','resize','keypress','select','keyup','submit','unload']; // These must be lower-case
//      var makeFunc = function(eventName) { return function() { dump('Got event '+eventName+'\n') } };
//      for (var i=0; i<events.length; i++) {
//        dump('reg '+events[i]+'\n');
//        newBrowser.addEventListener(events[i],makeFunc(events[i]), false);
//      }

}

};

